<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.username" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="flushEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="姓名" width="100">
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="200">
			</el-table-column>
			<el-table-column prop="phone" label="电话号码" width="150">
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="120">
			</el-table-column>
			<el-table-column prop="state" label="状态" min-width="100">
				<template scope="scope">
					<span v-if="scope.row.state === 1" style="color: #11b95c">工作</span>
					<span v-else-if="scope.row.state === 0" style="color: red">休息</span>
					<span v-else style="color: #8c939d">未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="department.name" label="所属部门">
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="currentPage"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="addForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱">
					<el-input v-model="addForm.email"></el-input>
				</el-form-item>
				<el-form-item label="电话号码">
					<el-input v-model="addForm.phone"></el-input>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="addForm.age"></el-input-number>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="addForm.state">
						<el-radio class="radio" :label="1">工作</el-radio>
						<el-radio class="radio" :label="0">休息</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="所属部门">
					<div class="block">
						<!--可通过 props.checkStrictly = true 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的。-->
						<!--:label 是用来显示的-->
						<!--:value="id" 用来传值得-->
						<el-cascader
								v-model="addForm.department"
								:options="depts"
								:props="{ checkStrictly: true, label:'name', value:'id' }"
								clearable></el-cascader>
					</div>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, editEmployee, addEmployee } from '../../api/api';

	export default {
		data() {
			return {
                depts:[],
			    title:'新增',
				filters: {
					name: ''
				},
				employees: [],
				total: 0,
				currentPage: 1,
				pageSize:5,
				listLoading: false,
				sels: [],//列表选中列

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
				    id:null,
					username: '',
					email: '',
					phone: null,
					age: null,
					state: 1,
                    department:null
				}

			}
		},
		methods: {
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getEmployees();
			},
			//获取员工列表
			getEmployees() {
				let para = {
					currentPage: this.currentPage,
					pageSize:this.pageSize,
					username: this.filters.name
				};
				this.listLoading = true;
				//NProgress.start();
				this.$http.post("/emp", para).then(res => {
                    this.total = res.data.total;
                    this.employees = res.data.rows;
                    this.listLoading = false;
                    //NProgress.done();
				})
			},
			//刷新员工列表（跳转到第一页）
            flushEmployees() {
				let para = {
					currentPage: 1,
					pageSize:this.pageSize,
					username: this.filters.username
				};
				this.currentPage = para.currentPage;
				this.listLoading = true;
				//NProgress.start();
				this.$http.post("/emp", para).then(res => {
                    this.total = res.data.total;
                    this.employees = res.data.rows;
                    this.listLoading = false;
                    //NProgress.done();
				})
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/emp/" + row.id).then((res) => {
                        if(res.data.success){
                            this.$message({
                                message:res.data.msg,
                                type:'success'
                            })
                        }else{
                            this.$message({
                                message:res.data.msg,
                                type:'error'
                            })
                        }
                        this.listLoading = false;
						this.getEmployees();
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			    this.title = '编辑';
				this.addFormVisible = true;
				// 回显数据
				let para = Object.assign(this.addForm, row);
                // 上级部门回显的调整
                if(row.department){
                    para.department = para.department.id;
                }
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
                    id:null,
					username: '',
					email: '',
					phone: null,
					age: null,
					state: 1,
                    department:null
                }
			},
			//新增或编辑
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
                    if (valid){// 通过验证
                        this.$confirm('确认提交该数据吗?', '提示', {}).then(() =>{
                            this.addLoading = true;
                            // 获取当前表单数据
                            let param = Object.assign({}, this.addForm);
                            if(param.department != null){
                                let ids = param.department;
                                param.department = {
                                    id:ids[ids.length - 1]
                                }
                            }
                            // 提交表单
                            this.$http.put("/emp", param).then(res =>{
                                if(res.data.success){
                                    this.$message({
                                        message:res.data.msg,
                                        type:'success'
                                    })
                                    this.getEmployees();
                                }else{
                                    this.$message({
                                        message:res.data.msg,
                                        type:'error'
                                    })
                                }
                                this.addFormVisible = false;
                                this.addLoading = false;
                            })
                        })
                    }
				})
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				let ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/emp", ids).then((res) => {
                        if(res.data.success){
                            this.$message({
                                message:res.data.msg,
                                type:'success'
                            })
                        }else{
                            this.$message({
                                message:res.data.msg,
                                type:'error'
                            })
                        }
                        this.listLoading = false;
                        this.getEmployees();
					});
				}).catch(() => {

				});
			},
            getDepts: function(){
                this.$http.get("/dept/getTree").then(res => {
                    this.depts = this.getDeptsData(res.data);
                })
            },
            // 处理获取到的部门树数据
            getDeptsData(data){
                for(let i; i < data.length; i++){
                    if (data[i].children.length < 1){// children为空数组，则将children设为undefined
                        data[i].children = undefined;
                    }else {// children不为空数组，则继续递归调用此方法
                        this.getDeptsData(data[i].children);
                    }
                }
                return data;
            }
		},
		mounted() {
			this.getEmployees();
			this.getDepts();
		}
	}

</script>

<style scoped>

</style>